package com.mystudy.leetcode.problem.link.p_25;

import com.mystudy.leetcode.base.ListNode;
import com.mystudy.leetcode.base.ListNodeUtils;
import org.junit.Test;

/**
 * @author 周志龙
 * @Email 15216876513@163.com
 * @Date on 2019/7/9 22:29
 * @Description K个一组翻转链表
 */
public class Solution {

    @Test
    public void test(){
        ListNode listNode = ListNodeUtils.generateLinkList(new int[]{1, 2, 3, 4, 5});
        ListNode listNode1 = reverseKGroup(listNode, 2);
        ListNodeUtils.show(listNode1);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode prev = dummyHead;
        ListNode cur = head;

        int x = 1;
        while (cur != null) {
            if (x % k == 0) {
                ListNode p = prev;
                ListNode c = prev.next;
                while (c != cur) {
                    ListNode nextTemp = c.next;
                    c.next = nextTemp.next;
                    nextTemp.next = c;
                    p.next = nextTemp;
                }
                cur = c.next;
                prev = c;
            } else {
                cur = cur.next;
            }
            x++;
        }

        return dummyHead.next;
    }


}
